import os.path
import re
import sys

idx_comment = 9
idx_table_name = 10
idx_table_name_upper = 11


def word2Camel(word):
    new_word = word[0]
    for i in range(1, len(word)):
        if word[i - 1] != '_' and word[i] != '_':
            new_word += word[i]
        elif word[i] != '_':
            new_word += word[i].upper()
    return new_word


def getType(word):
    word_type = ''
    if 'bigint' in word:
        word_type = 'Long'
    elif ('int' in word) or ('tinyint' in word):
        word_type = 'Integer'
    elif 'varchar' in word:
        word_type = 'String'
    elif 'timestamp' in word:
        word_type = 'Timestamp'
    elif 'bit' in word:
        word_type = 'Boolean'
    elif 'double' in word:
        word_type = 'Double'
    return word_type


def arrayPrinter(array, file):
    for line in array:
        file.write(line + '\n')
    file.write('\n')


def getCommentIndex(seq):
    for i in range(len(seq)):
        if seq[i] == 'COMMENT':
            return i + 1
    return -1


if __name__ == '__main__':
    file_name = sys.argv[1]
    if not os.path.isdir("out"):
        os.mkdir("out")
    with open(file_name, mode='r', encoding='utf-8') as file:
        lines = file.readlines()
        index = 0
        while index < len(lines):
            if not lines[index].startswith('CREATE'):
                index += 1
                continue
            table_name = re.search(r"`(\w+)`", lines[index].split()[2]).group(1)
            line_list = ['import com.baomidou.mybatisplus.annotation.*;',
                         'import io.swagger.annotations.*;',
                         'import lombok.*;',
                         '',
                         'import java.sql.Timestamp;',
                         '',
                         '@Data',
                         '@NoArgsConstructor',
                         '@AllArgsConstructor',
                         '@ApiModel("comment")',
                         '@TableName("`table_name`")',
                         'public class table_name_upper {']
            line_list[idx_table_name] = line_list[idx_table_name].replace('table_name', table_name)
            line_list[idx_table_name_upper] = line_list[idx_table_name_upper].replace('table_name_upper', word2Camel(table_name.capitalize()))
            index += 1
            first = True
            while not lines[index].startswith(')'):
                seq = lines[index].split()
                if re.fullmatch(r'`\w+`', seq[0]) is None:
                    index += 1
                    continue

                word = seq[0].strip('`')
                word = word2Camel(word)

                word_type = getType(seq[1])

                if not first:
                    comment_index = getCommentIndex(seq)
                    if comment_index != -1:
                        line_list.append('\n\t@ApiModelProperty("' + seq[comment_index][:-1].strip("'") + '")')
                    line_list.append('\t@TableField("' + seq[0] + '")')
                else:
                    line_list.append('\n\t@ApiModelProperty("主键")')
                    line_list.append('\t@TableId(value = "' + seq[0] + '", type = IdType.ASSIGN_ID)')
                    first = False
                line_list.append('\tprivate ' + word_type + ' ' + word + ';')

                index += 1
            comment = lines[index].split()[-1]
            comment = re.search(r"'(.*)'", comment).group(1)
            line_list[idx_comment] = line_list[idx_comment].replace('comment', comment)
            line_list.append('}')
            with open('./out/' + word2Camel(table_name.capitalize()) + '.java', mode='w', encoding='utf-8') as out:
                arrayPrinter(line_list, out)
            index += 1
